/**
 * JavaScript Document
 * @author sijian zhang
 * charset=utf-8
 */
(function(){
    
	$obj = window.$obj = function(id) {
		return new $sj.obj(id);
	}
	
	
	$sj = $obj.fn = $obj.prototype = {
		/**
		 * 初始化全局变量
		 */
        init:function(){
			window.HTML = document.getElementsByTagName("HTML")[0];
			window.HEAD = document.getElementsByTagName("HEAD")[0];
			window.BODY = document.getElementsByTagName("BODY")[0];
			window.DOC  = $sj.getDoc();
			window.Temp = $sj.Map();
			window.IE6 = function(){if(window.ActiveXObject && !window.XMLHttpRequest){return true}else{return false}}()
			window.IE7 = function(){if(window.ActiveXObject && window.XMLHttpRequest){return true}else{return false}}()
        },
		insertHtml :function (el, html,where , callback){
			where = where || "afterbegin";
			where = where.toLowerCase();
			if(el.insertAdjacentHTML){
				var tag = el.tagName;
				if(tag == "STYLE"){
					el.styleSheet.cssText += html;
					return;
				}
				if(tag == "SELECT"){
					var reMultiTag = /<\s*([\w\:]+)/g
					text = html.match(reMultiTag);
					//alert(text)
					value = where || "";
					el.options.add( new Option(text , value) )
					return;
				}
				if(tag == "TABLE" || tag == "TBODY" || tag == "THEAD" || tag == "TFOOT"){
					var trTag = /<(tr)\s*[^<>]*>(.*?)(<\/\1\s*>)/ig;
					var trStar = /^<(tr)\s*[^<>]*>/ig;
					var tdTag = /<(td)\s*[^<>]*>(.*?)(<\/\1\s*>)/ig;
					var tdStar = /^<(td)\s*[^<>]*>/ig;
					var delTag = /\w*(=)(\S[^<>]*)/ig;
					
					var trs = html.match(trTag);
					if(!trs){alert("传入的字符串不是表格行") ; return false}
					//var addRows = trs.length ;
					
					//var addCells ;
					var rows  = (function(){if(where == "beforebegin" || "afterbegin"){return 0}else{return el.getElementsByTagName("TR").length + 1 }})();
					for(i=0;i<trs.length;i++){
						//开始添加行
						var addNewRow = el.insertRow(rows);
						//把tr(通常在第一个)标签提取出来
						var thisTR = trs[i].match(/(<)(\S[^<>]*)(>)/ig)[0]
						//alert(thisTR)
						var newRowTds = trs[i].match(tdTag)
						//alert(trs[i])//.replace()
						//提取属性
						var addatt = thisTR.match(delTag);
						//alert(addatt)
						//alert(trStr)
						tds = trs[i].match(tdTag);
						//alert(tds)
						//addCells = tds.length ;
						//开始添加表格
						for(j=0 ; j<tds.length ;j++){
							//alert(tds[j].match(tdStar))
							var addNewTD = addNewRow.insertCell(j)
							addNewTD.innerHTML= tds[j].match(/([^>]{1})(\S*)([^<]{1})/ig).toString()
							alert(tds[j].match(/([^<td> |>][^>]\S*)(\S*)([^<|t|d|>]\S*)*>/ig))
						}
						//新的一个想法，先添加table标签，把table插入到隐藏区域，再把tr复制到需要的位置上
						//alert(trs[i])
						//var firstCell = addRows.insertCell()
						//el = firstCell;
						//(function(){el.insertAdjacentHTML('AfterBegin', html)})();
						rows + 1 ;
					}
					
					
					//alert(tag +"插入功能尚未实现'" )
					
					
					
							$obj("outPut")
					var tempHtml = "" ;
					alert(text.length)
					for(i=0; i<text.length ;i++){
						alert(text[i])
						tempHtml += "<li>" + text[i] + "</li>"
					}
					//$obj("outPut").innerHTML = tempHtml;
					
					return
				}
				if(tag == "TR"){
					//alert(tag +"插入功能尚未实现:'" + html +"'未插入")
				}
				else{
					var insertOf = {
							beforebegin: function(){el.insertAdjacentHTML('BeforeBegin', html); return el.previousSibling;},
							afterbegin: function(){el.insertAdjacentHTML('AfterBegin', html); return el.firstChild;},
							beforeend: function(){el.insertAdjacentHTML('BeforeEnd', html); return el.lastChild;},
							afterend: function(){el.insertAdjacentHTML('AfterEnd', html); return el.nextSibling;}
						}
					insertOf[where]()
					return;
				}
			}/*ie end*/
			/*ff star*/
			else{
				var range = el.ownerDocument.createRange();  
	    		var frag;
				var insertOf = {
					beforebegin: function(){
						range.setStartBefore(el);
						frag = range.createContextualFragment(html);
						el.parentNode.insertBefore(frag, el);
						return el.previousSibling;
					},
					afterbegin: function(){
						if(el.firstChild){
							range.setStartBefore(el.firstChild);
							frag = range.createContextualFragment(html);
							el.insertBefore(frag, el.firstChild);
							return el.firstChild;
						}
						else{
							el.innerHTML = html;
							return el.firstChild;
						}
					},
					beforeend: function(){
						if(el.lastChild){
							range.setStartAfter(el.lastChild);
							frag = range.createContextualFragment(html);
							el.appendChild(frag);
							return el.lastChild;
							}
						else{
							el.innerHTML = html;
							return el.lastChild;
						}
					},
					afterend: function(){
						range.setStartAfter(el);
						frag = range.createContextualFragment(html);
						el.parentNode.insertBefore(frag, el.nextSibling);
						return el.nextSibling;
					}
				}
				insertOf[where]()
			}
			
		},
        obj : function(id){
            return document.getElementById(id) ;
        },
		ifmLoader: function(url , ids , where){
			var iframe = document.createElement("iframe");
			iframe.src = url;
			var copyTo = $obj(ids);
			var docTemp ;
			
			if (iframe.attachEvent){
			    iframe.attachEvent("onload", function(){
					docTemp = iframe.contentWindow.document.body.innerHTML;
					$sj.insertHtml(copyTo , docTemp, where)
					iframe.removeNode(true)
				});
			}
			else {
			    iframe.onload = function(){
					var docs = iframe.contentDocument.documentElement || "";
					docTemp = docs.getElementsByTagName("body")[0].innerHTML;
					$sj.insertHtml(copyTo , docTemp, where)
					var removeIframe = function(){iframe.parentNode.removeChild(iframe)};
					setTimeout(removeIframe , 1000);
					//iframe.parentNode.removeChild(iframe)
				};
			}
			document.body.appendChild(iframe);
			
			
		},
		getId : function(id){
			obj = function(id){
				return document.getElementById(id)
			}
			obj.prototype = $sj.util
			
			return new obj(id)
		},
		getDoc : function() {
	        return (document.compatMode != "CSS1Compat") ? document.body : document.documentElement;
	    },
		getIframeDoc : function(ifmId){
			iframe =  $obj(ifmId) || ifmId
			return iframe.contentDocument.document.body.innerHTML || iframe.contentWindow.document
		},
        getTagNameObj: function(tag){
            return document.getElementsByTagName(tag) || document.getElementsByTagName("*");
        },
        getClassObj : function(className){
			if(document.getElementsByClassName){
				return  document.getElementsByClassName(className)
			}
			else{
				ret = new Array();
				fn = function(obj){
					if(obj.className.indexOf(className) != -1){
						ret.push(obj)
					}
				}
				$sj.forEach($sj.getTagNameObj("*") , fn)
				return ret;
			}
        },
		
		loader : function(url){
			this.src = url.replace(new RegExp(".js"),"")
			if(document.getElementById(this.src + "Js" + "Load")){return}
			else
			this.scriptDoc = document.createElement('script')
			this.scriptDoc.src = this.src + ".js";
			this.scriptDoc.id = this.src + "Js" + "Load";
			document.getElementsByTagName("HEAD")[0].appendChild(this.scriptDoc)
		},
		loadCss: function(url){
			this.href = url.replace(new RegExp(".css"),"")
			if(document.getElementById(this.href + "Css" + "Load")){return}
			else
			this.Css = document.createElement('link')
			this.Css.href = this.href + ".css";
			this.Css.type = "text/css";
			this.Css.rel = "stylesheet";
			this.Css.id = this.href + "Css" + "Load";
			document.getElementsByTagName("HEAD")[0].appendChild(this.Css)
		},
        forEach : function(list, fun){
			for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
		},
		sys :function(){
			var ua = navigator.userAgent.toLowerCase();
			(s = ua.match(/msie ([\d.]+)/)) ? undefined :
			(s = ua.match(/firefox\/([\d.]+)/)) ? undefined :
			(s = ua.match(/chrome\/([\d.]+)/)) ? undefined :
			(s = ua.match(/opera.([\d.]+)/)) ? undefined :
			(s = ua.match(/version\/([\d.]+).*safari/)) ? undefined : 0;
			return s;
		},
		Extend : function(){
			for (var i = 0, l = arguments.length; i < l; i++){
				arguments[i].extend = function(props){
					for (var prop in props){
						if (!this.prototype[prop]) this.prototype[prop] = props[prop];
						if (!this[prop]) this[prop] = function(prop){
							return function(bind){
								return this.prototype[prop].apply(bind, Array.prototype.slice.call(arguments, 1));
							};
						};
					}
				};
			}
		},
		$extend : function(){
			var args = arguments;
			if (!args[1]) args = [this, args[0]];
			for (var property in args[1]) args[0][property] = args[1][property];
			return args[0];
		},
		Map: function(NewMap){
			classMap = function(){
				this.map = {};
				this.length = 0;
				this.size = function(){
				   return this.length;
				}
				this.put = function(key, value){
				  if( !this.map["_" + key]){
						 ++this.length;
					}
				  this.map["_" + key] = value;
				}
				this.remove = function(key){
				   if(this.map["_" + key]){
					  --this.length;
					return delete this.map["_" + key];
				  }
				  else{
					  return false;
				  }
				}
				this.hasKey = function(key){
				 return this.map["_" + key] ? true:false;
				}
				this.get = function(key){
				  return this.map["_" + key] ? this.map["_" + key]:null;
				}
				this.inspect=function(){    
				 var str = "";
				 for(var each in this.map){
					  str+= "\n"+ each + "  Value:"+ this.map[each];
				 }
				 return str;
				}
			}
			return (NewMap = new classMap());
		}//mapEnd
    }//fn.end
	
	
})()

/**
 * Extend util
 */

$sj.util = {
    addEvent:function (eventType, fn ,obj ){
		obj = document.getElementById(obj) || obj || this;
		if (obj.addEventListener){
			obj.addEventListener(eventType, fn , false );
		}
		else if (obj.attachEvent){
			obj.attachEvent("on" + eventType, fn);
		}
		return obj
	},
	removeEvent : function(eventType, fn ,obj) {
		obj = document.getElementById(obj) || obj || this;
		if (obj.removeEventListener){
			obj.removeEventListener(eventType , fn, false);
		} else if (obj.detachEvent){
			obj.detachEvent('on' + eventType , fn);
		}
		return obj
	},
	addClass : function(cla , obj){
		
		ele = document.getElementById(obj) || obj || this;
		if (ele.className.indexOf(cla) == -1){
			ele.className = (ele.className + " " + cla).split(new RegExp(/\s^2/));
		}
		
		return ele;
	},
	removeClass : function(cla,obj){
		ele = document.getElementById(obj) || obj || this;
		ele.className = ele.className.toString().replace(new RegExp(cla) , "");
		return ele;
	},
	hasClass : function(cla,obj){
		return obj.className.toString().indexOf(cla)
	},
	hidden : function(obj){
		obj = document.getElementById(obj) || obj || this;
		obj.style.visibility = "hidden";
		obj.style.position = "absolute";
	},
	show :function(obj){
		obj = document.getElementById(obj) || obj || this;
		obj.style.visibility = "";
		obj.style.position = "";
	},
	setOpacity : function(opacity , obj) {
		obj = document.getElementById(obj) || obj || this;
		if (window.ActiveXObject) {
			obj.style.filter = (opacity == 100) ? "" : "alpha(opacity=" + opacity + ")";  //gray()  灰化滤镜 
		} else {
			obj.style.opacity = (opacity == 100) ? "" : "0." + opacity.toString();
		}
		return obj;
	},
	
	getObjHeight: function(el) {
		el = document.getElementById(el) || el || this || $sj.getDoc()
		return Math.max(el.scrollHeight, el.clientHeight);
	},
	getObjWidth: function(el) {
		el =  document.getElementById(el) || el || this || $sj.getDoc()
		return Math.max(el.scrollWidth, el.clientWidth);
	},
	getMousePos : function() {
		ev = arguments[0] || window.event;
		el = $sj.getDoc();
		return {"x" : ev.clientX + el.scrollLeft - el.clientLeft ,"y" : ev.clientY + el.scrollTop - el.clientTop}||{ "x" : ev.pageX, "y" : ev.pageY};
	},
	getObjPos : function(el) {
		el = $obj(el) || el || this || $sj.getDoc()
		el.x = 0;
		el.y = 0;
		if (el.getBoundingClientRect) {
			box = el.getBoundingClientRect();
			el = $sj.getDoc();
			el.x = box.left + el.scrollLeft - el.clientLeft;
			el.y = box.top + el.scrollTop - el.clientTop;
			box = null
		} else {
			el.x = el.offsetLeft;
			el.y = el.offsetTop;
			var parent = el.offsetParent;
			while (parent) {
				el.x += parent.offsetLeft;
				el.y += parent.offsetTop;
				parent = parent.offsetParent;
			}
			parent = null
		}
		return {"x" : el.x , "y" : el.y};
	}
	//Extend end
}
/**
 * Example:
 * $sj.Extend(Function, Array, String, Number , Object)
 * Object.extend($sj.util)  //将$sj.util 作为 Object 的扩展
 */

$sj.Extend(Function, Array, String, Number , Object)
//Object.extend($sj.util)

